import { defineStore } from 'pinia'
import { useRouteStore } from './router'
import { fetchLogin } from '@/service'
import { router } from '@/router'
import { local } from '@/utils'

export const useAuthStore = defineStore('auth-store', {
  state: () => {
    return {
      isRefreshAvatar: false,
      userInfo: local.get('userInfo'),
      token: local.get('accessToken') || ''
    }
  },
  getters: {
    // 是否登录
    isLogin(state) {
      return Boolean(state.token)
    }
  },
  actions: {
    changIsRefreshAvatar() {
      this.isRefreshAvatar = !this.isRefreshAvatar
    },
    // 登录退出，重置用户信息等
    async logout() {
      const route = unref(router.currentRoute)
      // 清除本地缓存
      this.clearAuthStorage()
      // 重置当前存储库
      this.$reset()
      // 重定向到登录页
      if (route.meta.requiresAuth) {
        router.push({
          name: 'login',
          query: {
            redirect: route.fullPath
          }
        })
      }
    },
    clearAuthStorage() {
      local.remove('accessToken')
      local.remove('userInfo')
    },
    // 用户登录
    async login(loginValue) {
      try {
        const res = await fetchLogin(loginValue)
        if (res.status !== 200) return res.message
        if (res.message === 'User not registered') return '该用户尚未注册,请先注册后再登录!'
        if (res.message === 'Password error') return '密码错误,请重新输入!'
        if (res.message === 'Disabled user') return '该用户已被禁用,请联系管理员启用!'
        // 处理登录信息
        await this.handleLoginInfo(res.data)
      } catch (e) {
        return e.message ?? e.data
      }
    },
    // 处理登录返回的数据
    async handleLoginInfo(data) {
      local.set('userInfo', data)
      // 将 token 保存下来
      local.set('accessToken', data.token)
      this.token = data.token
      this.userInfo = data
      // 添加路由和菜单
      const routeStore = useRouteStore()
      await routeStore.initAuthRoute()
      // 进行重定向跳转
      const route = unref(router.currentRoute)
      const query = route.query
      router.push({
        path: query.redirect || '/'
      })
    }
  }
})
